package my.mywork1;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import work.netty.*;

import java.nio.charset.Charset;


public class EchoServer {

    private NetServer netServer;

    private int num=2;

    public EchoServer(){

    }

    public EchoServer(int num) {
        this.num = num;
    }

    private NettyChannelAdapter channelAdapter = new NettyChannelAdapter() {

        public void channelConnected(NettyChannelHandler handler) {
            // TODO Auto-generated method stub

        }

        public boolean authenticate(NettyChannelHandler handler, ByteBuf byteBuf) {
            // TODO Auto-generated method stub
            String s= byteBuf.toString(Charset.defaultCharset());
            System.out.println("receive:"+s);
            return true;
        }

        public void channelAuthenticated(NettyChannelHandler handler) {
            // TODO Auto-generated method stub

        }

        public void channelRead(NettyChannelHandler handler, ByteBuf byteBuf) {
            // TODO Auto-generated method stub
            String s= byteBuf.toString(Charset.defaultCharset());
//            System.out.println("receive:"+s);
            for(int i=0;i<num;i++) {
                handler.writeAndFlush(NettyUtils.safeDuplicate(byteBuf));
            }
        }

        public void channelDisconnected(NettyChannelHandler handler) {
            // TODO Auto-generated method stub

        }

        public void eventTriggered(NettyChannelHandler handler, Object evt) {
            // TODO Auto-generated method stub


        }

        public void exceptionCaught(NettyChannelHandler handler, Throwable cause) {
            // TODO Auto-generated method stub
            System.out.println(cause.getMessage());
        }

    };

    public void start(String ip,int port) {
        netServer=new NetServer();
        netServer.setIpAddr(new IpAddress(ip, port));
        netServer.setAdvisor(new ChannelAdvisor() {

            public void initChannel(SocketChannel socketchannel) {
                // TODO Auto-generated method stub
                ChannelPipeline pipeline = socketchannel.pipeline();
                NettyChannelHandler handler = new NettyChannelHandler(channelAdapter);
                pipeline.addLast("handler", handler);
            }

            public void bindSuccess() {
                // TODO Auto-generated method stub

            }

            public void bindFailure() {
                // TODO Auto-generated method stub

            }

            public void bindClose() {
                // TODO Auto-generated method stub

            }


        });

        netServer.start();


    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        EchoServer echoServer=new EchoServer();
        echoServer.start("127.0.0.1",6401);

    }
}
